package org.firebug.spring.boot.hikari.controller.api;

import org.firebug.common.bean.api.Meta;
import org.firebug.common.bean.api.Response;
import org.firebug.spring.boot.hikari.controller.dto.UserDto;
import org.firebug.spring.boot.hikari.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/user")
public class UserApi {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Response save(@Validated @RequestBody UserDto dto, Errors errors) {
        if(errors.hasErrors()) {
            return Response._400;
        }
        userService.save(dto);
        return Response._200;
    }

    @RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
    public Response remove(@PathVariable Long id) {
        userService.removeById(id);
        return Response._200;
    }

    @RequestMapping(value = "/modify/{id}", method = RequestMethod.PUT)
    public Response modify(@PathVariable Long id, @Validated @RequestBody UserDto dto, Errors errors) {
        dto.setId(id);
        if(errors.hasErrors()) {
            return Response._400;
        }
        userService.modifyById(dto);
        return Response._200;
    }

    @RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
    public Response<UserDto> query(@PathVariable Long id) {
        UserDto dto = userService.queryById(id);
        return Response.newInstance(Meta._200, dto);
    }
}

